package com.dormitory.management.system.service.impl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.dormitory.management.system.DAO.UpLoadCostExcelFileDao;
import com.dormitory.management.system.entity.*;

import com.dormitory.management.system.enums.StatusEnum;
import com.dormitory.management.system.enums.UserEnum;
import com.dormitory.management.system.listener.UpLoadCostExcelFileListener;

import com.dormitory.management.system.mapper.*;
import com.dormitory.management.system.req.CostSaveReq;
import com.dormitory.management.system.resp.CostResp;
import com.dormitory.management.system.req.CostPageReq;
import com.dormitory.management.system.resp.StuAndHouResp;
import com.dormitory.management.system.service.CostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dormitory.management.system.service.UserService;
import com.dormitory.management.system.utils.AliPayUtil;
import com.dormitory.management.system.utils.EmailUtil;
import com.dormitory.management.system.utils.QrCodeUtil;
import com.dormitory.managemnet.util.core.Result;
import com.dormitory.managemnet.util.utils.BeanUtil;
import com.google.zxing.common.BitMatrix;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 水电费用表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-12-17
 */
@Service
public class CostServiceImpl extends ServiceImpl<CostMapper, Cost> implements CostService {

    @Autowired
    private UserService userService;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private HousemasterMapper housemasterMapper;
    @Autowired
    private AliPayUtil aliPayUtil;
    @Autowired
    private UpLoadCostExcelFileDao upLoadCostExcelFileDao;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private LivingMapper livingMapper;

    @Override
    public boolean save(CostSaveReq req) {
        return this.baseMapper.insert(BeanUtil.copyProperties(req,Cost.class))>0;
    }

    @Override
    public BitMatrix pay(Long id) {
        Cost cost = this.baseMapper.selectById(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        Room room = roomMapper.selectById(cost.getRoomId());
        Building building = buildingMapper.selectById(room.getBuildingId());
        Living living = livingMapper.selectById(building.getLivingId());
        //缴费信息 生成二维码图片
        return QrCodeUtil.createQrCode(aliPayUtil.faceToFacePay(living.getLiving()+"-"+building.getBuilding()+"-"+room.getRoom()+" 水电支付",date + id.toString(), cost.getCostTotal().toString()));
    }

    @Override
    public boolean delete(Long id) {
        return this.baseMapper.deleteById(id)>0;
    }

    @Override
    public String updateStatus(HttpServletRequest req) {
        //根据回调信息判断支付情况
        return aliPayUtil.notifyUrl(req);
    }


    @Override
    public IPage<CostResp> getPage(CostPageReq req) {
        if (userService.getRoleKey(req.getUsername()).equals(UserEnum.USER_HOUSEMASTER.getRoleKey())) {
            Housemaster housemaster = housemasterMapper.selectOne(new QueryWrapper<Housemaster>().lambda().eq(Housemaster::getIdentityCard, req.getUsername()));
            return this.baseMapper.getCostPage(new Page<>(req.getPageCurrent(),req.getPageSize()),new QueryWrapper<CostResp>()
                    .eq("r.building_id",housemaster.getBuildingId())
                    .eq("c.status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                    .like(req.getRoom()!=null,"room",req.getRoom())
                    .like(req.getCostTotal()!=null,"cost_total",req.getCostTotal())
                    .apply(req.getGmtCreate()!=null,"TO_DAYS(gmt_create) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtCreate(), "yyyy-MM-dd HH:mm:ss")+"')")
                    .apply(req.getGmtEnd()!=null,"TO_DAYS(gmt_create) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtEnd(), "yyyy-MM-dd HH:mm:ss")+"')"));
//                    .ge(req.getGmtCreate()!=null,"gmt_create",req.getGmtCreate())
//                    .le(req.getGmtEnd()!=null,"gmt_create",req.getGmtEnd()));
        }else if (userService.getRoleKey(req.getUsername()).equals(UserEnum.USER_STUDENT.getRoleKey())) {
            Student student = studentMapper.selectOne(new QueryWrapper<Student>().lambda().eq(Student::getStuId, req.getUsername()));
            return this.baseMapper.getCostPage(new Page<>(req.getPageCurrent(),req.getPageSize()),new QueryWrapper<CostResp>()
                    .eq("c.room_id",student.getRoomId())
                    .eq("status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                    .like(req.getCostTotal()!=null,"cost_total",req.getCostTotal())
                    .apply(req.getGmtCreate()!=null,"TO_DAYS(gmt_create) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtCreate(), "yyyy-MM-dd HH:mm:ss")+"')")
                    .apply(req.getGmtEnd()!=null,"TO_DAYS(gmt_create) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtEnd(), "yyyy-MM-dd HH:mm:ss")+"')"));
//                    .ge(req.getGmtCreate()!=null,"gmt_create",req.getGmtCreate())
//                    .le(req.getGmtEnd()!=null,"gmt_create",req.getGmtEnd()));
        }else {
            return this.baseMapper.getCostPage(new Page<>(req.getPageCurrent(),req.getPageSize()),new QueryWrapper<CostResp>()
                    .eq("status_id", StatusEnum.STATUS_NORMAL.getStatusId())
                    .like(req.getRoom()!=null,"room",req.getRoom())
                    .like(req.getCostTotal()!=null,"cost_total",req.getCostTotal())
                    .apply(req.getGmtCreate()!=null,"TO_DAYS(gmt_create) >= TO_DAYS('"+ DateFormatUtils.format(req.getGmtCreate(), "yyyy-MM-dd HH:mm:ss")+"')")
                    .apply(req.getGmtEnd()!=null,"TO_DAYS(gmt_create) <= TO_DAYS('"+ DateFormatUtils.format(req.getGmtEnd(), "yyyy-MM-dd HH:mm:ss")+"')"));
//                    .ge(req.getGmtCreate()!=null,"gmt_create",req.getGmtCreate())
//                    .le(req.getGmtEnd()!=null,"gmt_create",req.getGmtEnd()));
        }
    }

    public Result importWeekCheckByExcel(String username, MultipartFile file) throws IOException {
        if (!file.getResource().exists()){
            return Result.error("传入文件没有收到");
        }
        if (!"xlsx".equals(file.getOriginalFilename().split("\\.")[1])){
            return Result.error("请传入.xlsx格式文件");
        }
        /**
         * 通过阿里巴巴的EasyExcel进行excel文件和题库id的上传存储进数据库并发送邮件
         * UpLoadExcelFileListener监听器
         */
        EasyExcel.read(file.getInputStream(), CostExcel.class, new UpLoadCostExcelFileListener(upLoadCostExcelFileDao,username)).sheet().doRead();
        return Result.success("excel导入成功");
    }

}
